package com.skyolder.crutch.word.token.raw;

import com.skyolder.crutch.error.GrammarError;
import com.skyolder.crutch.word.raw.BufferCharQueue;
import com.skyolder.crutch.word.types.RawTokenType;

public class IdentifierTokenCreator implements TokenCreator {
	@Override
	public RawToken tryCreateToken(BufferCharQueue bufferCharQueue) throws GrammarError {
		StringBuilder stringBuilder=new StringBuilder();
		char c=bufferCharQueue.peekChar();
		if(!isLegalHead(c)){
			bufferCharQueue.back();
			return null;
		}
		bufferCharQueue.nextChar();
		stringBuilder.append(c);
		while(true){
			char cc=bufferCharQueue.peekChar();
			if(isLegal(cc)){
				stringBuilder.append(cc);
				bufferCharQueue.nextChar();
				continue;
			}
			break;
		}
		RawToken rToken=new RawToken(stringBuilder.toString(), RawTokenType.IDENTIFIER);
		return rToken;
	}
	private static boolean isLegal(char c){
		if(isLegalHead(c)){
			return true;
		}
		if(c>='0'&&c<='9'){
			return true;
		}
		if(c=='.'){
			return true;
		}		
		return false;
	}
	private static boolean isLegalHead(char c){
		if(c>='a'&&c<='z'){
			return true;
		}
		if(c>='A'&&c<='Z'){
			return true;
		}
		if(c=='_'){
			return true;
		}
		return false;
	}
}
